<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员规范库管理</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #2c3e50, #34495e);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 28px;
            margin-bottom: 10px;
        }
        
        .header p {
            opacity: 0.8;
            font-size: 16px;
        }
        
        .content {
            padding: 40px;
        }
        
        .section {
            margin-bottom: 40px;
            background: #f8f9fa;
            border-radius: 10px;
            padding: 30px;
        }
        
        .section h2 {
            color: #2c3e50;
            margin-bottom: 20px;
            font-size: 24px;
            border-bottom: 2px solid #3498db;
            padding-bottom: 10px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #2c3e50;
        }
        
        .form-group input, .form-group select, .form-group textarea {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
        }
        
        .form-group textarea {
            min-height: 100px;
            resize: vertical;
        }
        
        .btn {
            background: linear-gradient(135deg, #3498db, #2980b9);
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            transition: all 0.3s ease;
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(52, 152, 219, 0.4);
        }
        
        .btn-danger {
            background: linear-gradient(135deg, #e74c3c, #c0392b);
        }
        
        .btn-success {
            background: linear-gradient(135deg, #2ecc71, #27ae60);
        }
        
        .rule-list {
            margin-top: 20px;
        }
        
        .rule-item {
            background: white;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 15px;
            position: relative;
        }
        
        .rule-item h3 {
            color: #2c3e50;
            margin-bottom: 10px;
        }
        
        .rule-meta {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin: 15px 0;
            font-size: 14px;
        }
        
        .rule-meta span {
            background: #ecf0f1;
            padding: 5px 10px;
            border-radius: 5px;
        }
        
        .rule-actions {
            position: absolute;
            top: 15px;
            right: 15px;
        }
        
        .rule-actions button {
            margin-left: 10px;
            padding: 5px 10px;
            font-size: 12px;
        }
        
        .status {
            padding: 15px;
            border-radius: 8px;
            margin: 20px 0;
            font-weight: 600;
        }
        
        .status.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .status.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .tabs {
            display: flex;
            border-bottom: 1px solid #ddd;
            margin-bottom: 20px;
        }
        
        .tab {
            padding: 15px 30px;
            cursor: pointer;
            border: none;
            background: none;
            font-size: 16px;
            font-weight: 600;
            color: #7f8c8d;
            transition: all 0.3s ease;
        }
        
        .tab.active {
            color: #3498db;
            border-bottom: 3px solid #3498db;
        }
        
        .tab-content {
            display: none;
        }
        
        .tab-content.active {
            display: block;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🔐 管理员规范库管理</h1>
            <p>仅管理员可访问的规范知识库管理系统</p>
        </div>
        
        <div class="content">
            <div class="tabs">
                <button class="tab active" onclick="showTab('view')">📋 查看规范</button>
                <button class="tab" onclick="showTab('add')">➕ 添加规范</button>
                <button class="tab" onclick="showTab('import')">📥 导入导出</button>
            </div>
            
            <div id="status" class="status" style="display: none;"></div>
            
            <!-- 查看规范 -->
            <div id="view-tab" class="tab-content active">
                <div class="section">
                    <h2>当前规范库</h2>
                    <div id="rule-list" class="rule-list">
                        <p style="text-align: center; color: #7f8c8d; padding: 40px;">
                            正在加载规范库...
                        </p>
                    </div>
                </div>
            </div>
            
            <!-- 添加规范 -->
            <div id="add-tab" class="tab-content">
                <div class="section">
                    <h2>添加新规范</h2>
                    <form id="add-rule-form">
                        <div class="form-group">
                            <label>规范名称 *</label>
                            <input type="text" id="rule-name" required placeholder="例如：建筑防火规范">
                        </div>
                        
                        <div class="form-group">
                            <label>规范编号 *</label>
                            <input type="text" id="rule-code" required placeholder="例如：GB50016-2014">
                        </div>
                        
                        <div class="form-group">
                            <label>建筑类型 *</label>
                            <select id="building-type" required>
                                <option value="">请选择建筑类型</option>
                                <option value="residential">住宅建筑</option>
                                <option value="commercial">商业建筑</option>
                                <option value="office">办公建筑</option>
                                <option value="industrial">工业建筑</option>
                                <option value="educational">教育建筑</option>
                                <option value="medical">医疗建筑</option>
                                <option value="hotel">酒店建筑</option>
                                <option value="mixed">混合用途</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label>规则类别 *</label>
                            <select id="rule-category" required>
                                <option value="">请选择类别</option>
                                <option value="消防安全">消防安全</option>
                                <option value="结构安全">结构安全</option>
                                <option value="功能空间">功能空间</option>
                                <option value="无障碍设计">无障碍设计</option>
                                <option value="节能设计">节能设计</option>
                                <option value="通风采光">通风采光</option>
                                <option value="建筑设备">建筑设备</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label>严重程度 *</label>
                            <select id="severity" required>
                                <option value="">请选择严重程度</option>
                                <option value="严重">严重</option>
                                <option value="中等">中等</option>
                                <option value="轻微">轻微</option>
                                <option value="提示">提示</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label>检查条件 *</label>
                            <input type="text" id="condition" required placeholder="例如：stair_width < 1.1">
                        </div>
                        
                        <div class="form-group">
                            <label>阈值</label>
                            <input type="number" id="threshold" step="0.01" placeholder="例如：1.1">
                        </div>
                        
                        <div class="form-group">
                            <label>单位</label>
                            <input type="text" id="unit" placeholder="例如：米">
                        </div>
                        
                        <div class="form-group">
                            <label>规范描述 *</label>
                            <textarea id="description" required placeholder="详细描述规范要求..."></textarea>
                        </div>
                        
                        <div class="form-group">
                            <label>修复建议</label>
                            <textarea id="suggestion" placeholder="提供具体的修复建议..."></textarea>
                        </div>
                        
                        <button type="submit" class="btn btn-success">✅ 添加规范</button>
                    </form>
                </div>
            </div>
            
            <!-- 导入导出 -->
            <div id="import-tab" class="tab-content">
                <div class="section">
                    <h2>规范库管理</h2>
                    
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 30px;">
                        <div>
                            <h3>📤 导出规范库</h3>
                            <p>将当前规范库导出为JSON文件</p>
                            <button class="btn" onclick="exportRules()">导出规范库</button>
                        </div>
                        
                        <div>
                            <h3>📥 导入规范库</h3>
                            <p>从JSON文件导入规范库</p>
                            <input type="file" id="import-file" accept=".json" style="margin-bottom: 15px;">
                            <button class="btn" onclick="importRules()">导入规范库</button>
                        </div>
                    </div>
                    
                    <div style="margin-top: 30px;">
                        <h3>⚠️ 危险操作</h3>
                        <button class="btn btn-danger" onclick="clearAllRules()">清空所有规范</button>
                        <small style="display: block; margin-top: 10px; color: #e74c3c;">
                            警告：此操作将永久删除所有规范，请谨慎操作！
                        </small>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let currentRules = [];
        
        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadRules();
            document.getElementById('add-rule-form').addEventListener('submit', addRule);
        });
        
        // 标签页切换
        function showTab(tabName) {
            document.querySelectorAll('.tab').forEach(tab => tab.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
            
            document.querySelector(`.tab[onclick="showTab('${tabName}')"]`).classList.add('active');
            document.getElementById(`${tabName}-tab`).classList.add('active');
        }
        
        // 显示状态信息
        function showStatus(message, type = 'success') {
            const statusEl = document.getElementById('status');
            statusEl.textContent = message;
            statusEl.className = `status ${type}`;
            statusEl.style.display = 'block';
            
            setTimeout(() => {
                statusEl.style.display = 'none';
            }, 3000);
        }
        
        // 加载规范库
        async function loadRules() {
            try {
                const response = await fetch('/api/admin/rules');
                if (response.ok) {
                    currentRules = await response.json();
                    displayRules();
                } else {
                    throw new Error('加载失败');
                }
            } catch (error) {
                showStatus('加载规范库失败：' + error.message, 'error');
            }
        }
        
        // 显示规范列表
        function displayRules() {
            const ruleList = document.getElementById('rule-list');
            
            if (currentRules.length === 0) {
                ruleList.innerHTML = `
                    <p style="text-align: center; color: #7f8c8d; padding: 40px;">
                        规范库为空，请添加规范
                    </p>
                `;
                return;
            }
            
            ruleList.innerHTML = currentRules.map(rule => `
                <div class="rule-item">
                    <h3>${rule.title}</h3>
                    <div class="rule-meta">
                        <span><strong>编号：</strong>${rule.code}</span>
                        <span><strong>类型：</strong>${rule.building_type}</span>
                        <span><strong>类别：</strong>${rule.category}</span>
                        <span><strong>严重程度：</strong>${rule.severity}</span>
                        <span><strong>标准：</strong>${rule.standard}</span>
                        ${rule.threshold ? `<span><strong>阈值：</strong>${rule.threshold} ${rule.unit || ''}</span>` : ''}
                    </div>
                    <p><strong>描述：</strong>${rule.description}</p>
                    ${rule.suggested_fix ? `<p><strong>建议：</strong>${rule.suggested_fix}</p>` : ''}
                    <div class="rule-actions">
                        <button class="btn btn-danger" onclick="deleteRule('${rule.id}')">删除</button>
                    </div>
                </div>
            `).join('');
        }
        
        // 添加规范
        async function addRule(e) {
            e.preventDefault();
            
            const rule = {
                title: document.getElementById('rule-name').value,
                code: document.getElementById('rule-code').value,
                building_type: document.getElementById('building-type').value,
                category: document.getElementById('rule-category').value,
                severity: document.getElementById('severity').value,
                condition: document.getElementById('condition').value,
                threshold: parseFloat(document.getElementById('threshold').value) || null,
                unit: document.getElementById('unit').value || null,
                description: document.getElementById('description').value,
                suggested_fix: document.getElementById('suggestion').value || null,
                standard: document.getElementById('rule-code').value
            };
            
            try {
                const response = await fetch('/api/admin/rules', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Admin-Token': 'admin-secret-2024'
                    },
                    body: JSON.stringify(rule)
                });
                
                if (response.ok) {
                    showStatus('规范添加成功！');
                    document.getElementById('add-rule-form').reset();
                    loadRules();
                    showTab('view');
                } else {
                    throw new Error('添加失败');
                }
            } catch (error) {
                showStatus('添加规范失败：' + error.message, 'error');
            }
        }
        
        // 删除规范
        async function deleteRule(ruleId) {
            if (!confirm('确定要删除这条规范吗？此操作不可恢复！')) {
                return;
            }
            
            try {
                const response = await fetch(`/api/admin/rules/${ruleId}`, {
                    method: 'DELETE',
                    headers: {
                        'X-Admin-Token': 'admin-secret-2024'
                    }
                });
                
                if (response.ok) {
                    showStatus('规范删除成功！');
                    loadRules();
                } else {
                    throw new Error('删除失败');
                }
            } catch (error) {
                showStatus('删除规范失败：' + error.message, 'error');
            }
        }
        
        // 导出规范库
        function exportRules() {
            const dataStr = JSON.stringify(currentRules, null, 2);
            const dataBlob = new Blob([dataStr], {type: 'application/json'});
            const url = URL.createObjectURL(dataBlob);
            const link = document.createElement('a');
            link.href = url;
            link.download = `规范库_${new Date().toISOString().split('T')[0]}.json`;
            link.click();
            URL.revokeObjectURL(url);
            showStatus('规范库导出成功！');
        }
        
        // 导入规范库
        async function importRules() {
            const fileInput = document.getElementById('import-file');
            const file = fileInput.files[0];
            
            if (!file) {
                showStatus('请选择要导入的文件', 'error');
                return;
            }
            
            try {
                const text = await file.text();
                const rules = JSON.parse(text);
                
                const response = await fetch('/api/admin/rules/import', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Admin-Token': 'admin-secret-2024'
                    },
                    body: JSON.stringify(rules)
                });
                
                if (response.ok) {
                    showStatus('规范库导入成功！');
                    fileInput.value = '';
                    loadRules();
                } else {
                    throw new Error('导入失败');
                }
            } catch (error) {
                showStatus('导入规范库失败：' + error.message, 'error');
            }
        }
        
        // 清空所有规范
        async function clearAllRules() {
            if (!confirm('⚠️ 警告：此操作将永久删除所有规范！\n\n请输入 "DELETE_ALL" 确认删除：')) {
                return;
            }
            
            const confirmation = prompt('请输入 "DELETE_ALL" 确认删除：');
            if (confirmation !== 'DELETE_ALL') {
                showStatus('操作已取消', 'error');
                return;
            }
            
            try {
                const response = await fetch('/api/admin/rules/clear', {
                    method: 'DELETE',
                    headers: {
                        'X-Admin-Token': 'admin-secret-2024'
                    }
                });
                
                if (response.ok) {
                    showStatus('所有规范已清空！');
                    loadRules();
                } else {
                    throw new Error('清空失败');
                }
            } catch (error) {
                showStatus('清空规范库失败：' + error.message, 'error');
            }
        }
    </script>
</body>
</html>